const ComparePage = {
    async openPage(bizId, requestMethod, businessGuid, userGuid, tenantCode, mumHost, secretKid, secretK) {
        console.log(bizId + "," + requestMethod + "," + businessGuid + "," + userGuid + "," + tenantCode + "," + mumHost + "," + secretKid + "," + secretK);
        let compareWin = Utils.openWindowWithFavicon();
        this.initWindow(compareWin);

        compareWin.postMessage({data: `<h1>APP渠道对比</h1><div id="p-app">正在加载APP消息</div>`}, "*");
        compareWin.postMessage({data: `<h1>PC渠道对比</h1><div id="p-pc">正在加载PC消息</div>`}, "*");

        // 参数准备
        let local_headers = Config.local_headers;

        let remote_token = await EmcConfig.getMyAuthToken(secretKid, secretK);
        let remote_headers = {
            'Content-Type': 'application/json',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
            'Connection': 'keep-alive',
            'Accept': 'application/json',
            'tenantCode': tenantCode,
            'my-api-Authorization': remote_token
        }

        // app
        let remote_message1 = await this.getMumMessage(...arguments, 1, remote_headers);
        let remote_appMessage = remote_message1.data.length > 0 ? remote_message1.data[0] : {};
        let html = this.generateCompareTableHtml(remote_appMessage, {});
        compareWin.document.getElementById('p-app').innerHTML = html;

        let local_message1 = await this.getLocalMessage(...arguments, 1, local_headers);
        let local_appMessage = local_message1.data.length > 0 ? local_message1.data[0] : {};
        html = this.generateCompareTableHtml(remote_appMessage, local_appMessage);
        compareWin.document.getElementById('p-app').innerHTML = html;

        let local_messageExt = await this.getLocalDetailExt(...arguments, 1, local_headers);
        let remote_messageExt = await this.getMumDetailExt(...arguments, 1, remote_headers);

        this.mergeMessage(remote_appMessage, remote_messageExt, 1);
        this.mergeMessage(local_appMessage, local_messageExt, 1);
        html = this.generateCompareTableHtml(remote_appMessage, local_appMessage);
        compareWin.document.getElementById('p-app').innerHTML = html;
        this.compareTable(compareWin, 'p-app');


        // pc
        let remote_message2 = await this.getMumMessage(...arguments, 2, remote_headers);
        let remote_pcMessage = remote_message2.data.length > 0 ? remote_message2.data[0] : {};
        this.mergeMessage(remote_pcMessage, remote_messageExt, 2);
        html = this.generateCompareTableHtml(remote_pcMessage, {});
        compareWin.document.getElementById('p-pc').innerHTML = html;

        let local_message2 = await this.getLocalMessage(...arguments, 2, local_headers);
        let local_pcMessage = local_message2.data.length > 0 ? local_message2.data[0] : {};
        this.mergeMessage(local_pcMessage, local_messageExt, 2);
        html = this.generateCompareTableHtml(remote_pcMessage, local_pcMessage);
        compareWin.document.getElementById('p-pc').innerHTML = html;

        this.compareTable(compareWin, 'p-pc');
    },
    mergeMessage(appMessage, messageExt, msg_channel) {
        for (let i = 0; i < messageExt.data.length; i++) {
            let item = messageExt.data[i];
            if (typeof (item.msg_channel) != 'undefined' && item.msg_channel === msg_channel) {
                for (let key in item) {
                    appMessage[key] = item[key];
                }
            }
        }
    },
    async getLocalMessage(bizId, requestMethod, businessGuid, userGuid, tenantCode, mumHost, secretKid, secretK, clientType, headers) {
        let url = "http://localhost:8082/pub/40040901" + '/mum/v1/message/inquiry/user-messages';
        tenantCode = 'jmtest';
        userGuid = '4230bc6e-69e6-46a9-a39e-b929a06a84e8';
        let data = {
            "tenantCode": tenantCode,
            "bizId": bizId,
            "userGuid": userGuid.toLowerCase(),
            "clientType": clientType
        };
        return await RequestLocal.postLocal2(url, headers, data);
    },
    async getLocalDetailExt(bizId, requestMethod, businessGuid, userGuid, tenantCode, mumHost, secretKid, secretK, clientType, headers) {
        let url = "http://localhost:8082/pub/40040901" + '/mum/v1/message/inquiry/user-message-details';
        tenantCode = 'jmtest';
        userGuid = '4230bc6e-69e6-46a9-a39e-b929a06a84e8';
        let data = {
            "tenantCode": tenantCode,
            "bizId": bizId,
            "userGuid": userGuid.toLowerCase(),
            "clientType": clientType
        };
        return await RequestLocal.postLocal2(url, headers, data);
    },
    async getMumMessage(bizId, requestMethod, businessGuid, userGuid, tenantCode, mumHost, secretKid, secretK, clientType, headers) {
        let url = mumHost + '/mum/v1/message/inquiry/user-messages';
        let data = {
            "tenantCode": tenantCode,
            "bizId": bizId,
            "userGuid": userGuid.toLowerCase(),
            "clientType": clientType
        };
        return await RequestMum.postMum(url, headers, data);
    },
    async getMumDetailExt(bizId, requestMethod, businessGuid, userGuid, tenantCode, mumHost, secretKid, secretK, clientType, headers) {
        let url = mumHost + '/mum/v1/message/inquiry/user-message-details';
        let data = {
            "tenantCode": tenantCode,
            "bizId": bizId,
            "userGuid": userGuid.toLowerCase(),
            "clientType": clientType
        };
        return await RequestMum.postMum(url, headers, data);
    },

    generateCompareTableHtml(remote_appMessage, local_appMessage) {
        function format(item) {
            if (typeof (item.sender) == 'object') {
                item.sender = JSON.stringify(item.sender);
            }
        }

        format(local_appMessage);
        format(remote_appMessage);
        let html = `<table class="table table-bordered  auto-wrap-table">
        <thead>
            <tr>
                <th>字段</th>
                <th>remote</th>
                <th>local</th>
            </tr>
        </thead>
        <tbody>`;

        if (remote_appMessage && Object.keys(remote_appMessage).length > 0) {
            for (let key of Object.keys(remote_appMessage)) {
                html += `<tr>
                <td>${key}</td>
                <td>${remote_appMessage[key] !== undefined ? remote_appMessage[key] : ''}</td>
                <td>${local_appMessage && local_appMessage[key] !== undefined ? local_appMessage[key] : ''}</td>
            </tr>`;
            }
        } else if (local_appMessage && Object.keys(local_appMessage).length > 0) {
            for (let key of Object.keys(local_appMessage)) {
                html += `<tr>
                <td>${key}</td>
                <td>${remote_appMessage && remote_appMessage[key] !== undefined ? remote_appMessage[key] : ''}</td>
                <td>${local_appMessage[key]}</td>
            </tr>`;
            }
        } else {
            html += `<tr>
            <td>--</td>
            <td>None</td>
            <td>None</td>
        </tr>`;
        }

        html += `</tbody></table>`;
        return html;
    },
    compareTable(compareWin, div_id) {
        let tables = compareWin.document.getElementById(div_id).getElementsByTagName('table');
        if (tables.length === 0) {
            return;
        }
        let table = tables[0];
        table.querySelectorAll('tbody tr').forEach(function (row) {
            var oldCell = row.cells[1]; // 旧值
            var newCell = row.cells[2]; // 新值
            if (oldCell && newCell && oldCell.textContent !== newCell.textContent) {
                newCell.style.backgroundColor = '#ffeeba'; // 浅黄色高亮
            }
        });
    },
    initWindow(compareWin) {
        const style = compareWin.document.createElement('style');
        style.textContent = `
            .auto-wrap-table {
                table-layout: fixed;
                width: 100%;
                border-collapse: collapse;
            }
            .auto-wrap-table th,
            .auto-wrap-table td {
                border: 1px solid #ddd;
                padding: 8px;
                word-wrap: break-word;
                overflow-wrap: break-word;
            }
            .auto-wrap-table th:nth-child(1),
            .auto-wrap-table td:nth-child(1) {
                width: 10%;
            }
            .auto-wrap-table th:nth-child(2),
            .auto-wrap-table td:nth-child(2) {
                width: 45%;
            }
            .auto-wrap-table th:nth-child(3),
            .auto-wrap-table td:nth-child(3) {
                width: 45%;
            }
        `;
        compareWin.document.head.appendChild(style);

        const link = compareWin.document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css';
        link.integrity = 'sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu';
        link.crossOrigin = 'anonymous';
        compareWin.document.head.appendChild(link);

        const script = compareWin.document.createElement('script');
        script.text = `
            window.addEventListener('message', function(event) {
                if (event.data && event.data.data) {
                    const div = document.createElement('div');
                    div.innerHTML = event.data.data;
                    document.body.appendChild(div);
                }
            });
        `;
        compareWin.document.head.appendChild(script);
    }
};